<?php

/**
 * Created by JetBrains PhpStorm.
 * User: Grom Hellscream
 * Date: 11/2/12
 * Time: 1:19 PM
 * To change this template use File | Settings | File Templates.
 */
// No direct access to this file
defined('_JEXEC') or die('Restricted access');

// Include dependancy of the main model form
jimport('joomla.application.component.modelform');
// import Joomla modelitem library
jimport('joomla.application.component.modelitem');
// Include dependancy of the dispatcher
jimport('joomla.event.dispatcher');

/**
 * Tailieu Model
 */
class VastModelTailieu extends JModelForm {

    /**
     * @var object item
     */
    protected $_item;

    /**
     * Get the tailieu
     * @return object The tailieu to be displayed to the user
     */
    function getItem() {

        if (!isset($this->_item)) {
            $id = JRequest::getInt('tailieuid');
            
            $db = JFactory::getDBO();
            $query = $db->getQuery(true);

            $query->select('a.*');
            $query->from('#__tailieu AS a');
            $query->where('a.id = ' . $id);

            $db->setQuery($query);
            $tailieu = $db->loadObject();
            
            $this->_item = array();
            if (count($tailieu) > 0) foreach ($tailieu as $key => $value) {
                $this->_item[$key] = $value;
            }
        }
        
        return $this->_item;
    }
    
    public function createItem($data) {
        // set the data into a query to update the record
        $db = $this->getDbo();
        
        $file = JRequest::getVar('file_upload', null, 'files', 'array'); 
                
        if(isset($file)) { 
            //Clean up filename to get rid of strange characters like spaces etc
            $filename = JFile::makeSafe($file['name']);
 
            if($file['size'] > 1024 * 1024) return false;
            //Set up the source and destination of the file
 
            $src = $file['tmp_name'];
            
            $url = 'images' . DS . 'com_vast' . DS . $filename;
            $dest = JPATH_SITE . DS . 'images' . DS . 'com_vast' . DS . $filename;

            //First check if the file has the right extension, we need jpg only
            if ($file['type'] == 'application/pdf' 
                || $file['type'] == 'application/msword' 
                || $file['type'] == 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
                || $file['type'] == 'application/vnd.ms-powerpoint'
                || $file['type'] == 'application/vnd.openxmlformats-officedocument.presentationml.presentation') { 
                if ( JFile::upload($src, $dest) ) {
                    $data['dinhkem'] = $url;
                } else {
                    //Redirect and throw an error message
                    $this->setError(JText::_('COM_VAST_ERROR_IN_UPLOAD'));
                    return false;
                }
            } else {
                //Redirect and notify user file is not right extension
                $this->setError(JText::_('COM_VAST_FILE_TYPE_INVALID'));
                return false;
            } 

        }

        $query = 'INSERT INTO #__tailieu(`congtrinh_id`, `dinhkem`, `mota`)';
        $query .= ' VALUES(';
        $query .= (int)($data['congtrinh_id']) . ',' .
                  $db->quote($data['dinhkem']) . ',' .
                  $db->quote($data['mota']) . ')';                         
                
        $db->setQuery($query);
                                
        if (!$db->query()) {
            JError::raiseError(500, $db->getErrorMsg());
            return false;
        } else {
            return true;
        }
    }

    public function updateItem($data) {
        $id = JRequest::getInt('tailieuid');
        
        $file = JRequest::getVar('file_upload', null, 'files', 'array'); 
                
        if(isset($file)) { 
            //Clean up filename to get rid of strange characters like spaces etc
            $filename = JFile::makeSafe($file['name']);
 
            if($file['size'] > 1024 * 1024) return false;
            //Set up the source and destination of the file
 
            $src = $file['tmp_name'];
            
            $url = 'images' . DS . 'com_vast' . DS . $filename;
            $dest = JPATH_SITE . DS . 'images' . DS . 'com_vast' . DS . $filename;

            //First check if the file has the right extension, we need jpg only
            if ($file['type'] == 'application/pdf' 
                || $file['type'] == 'application/msword' 
                || $file['type'] == 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
                || $file['type'] == 'application/vnd.ms-powerpoint'
                || $file['type'] == 'application/vnd.openxmlformats-officedocument.presentationml.presentation') { 
                if ( JFile::upload($src, $dest) ) {
                    $data['dinhkem'] = $url;
                } else {
                    //Redirect and throw an error message
                    $this->setError(JText::_('COM_VAST_ERROR_IN_UPLOAD'));
                    return false;
                }
            } else {
                //Redirect and notify user file is not right extension
                $this->setError(JText::_('COM_VAST_FILE_TYPE_INVALID'));
                return false;
            } 

        }

        // set the data into a query to update the record
        $db = $this->getDbo();
        $query = $db->getQuery(true);
        $query->clear();
        $query->update('#__tailieu');
        
        foreach($data as $key => $value) {
            if (is_numeric($value)) {
                $query->set($key . ' = ' . $value);
            } else {
                $query->set($key . ' = ' . $db->quote($value));
            }
        }
        
        $query->where('id = ' . $id);
        
        $db->setQuery($query);
        
        if (!$db->query()) {
            JError::raiseError(500, $db->getErrorMsg());
            return false;
        } else {
            return true;
        }
    }
    
    public function deleteItem($tailieuid)
    {        
        // set the data into a query to update the record
        $db = $this->getDbo();

        $query = 'DELETE FROM #__tailieu WHERE `id` = ' . (int)$tailieuid;
                
        $db->setQuery($query);
        
        if (!$db->query()) {
            JError::raiseError(500, $db->getErrorMsg());
            return false;
        } else {
            return true;
        }        
    }
    
    public function getForm($data = array(), $loadData = true) {
        // Get the form.
        $form = $this->loadForm('com_vast.tailieu', 'tailieu', array('control' => 'jform', 'load_data' => true));
        if (empty($form)) {
            return false;
        }
        $jinput = JFactory::getApplication()->input;

        // The front end calls this model and uses a_id to avoid id clashes so we need to check for that first.
        if ($jinput->get('a_id')) {
            $id = $jinput->get('a_id', 0);
        }
        // The back end uses id so we use that the rest of the time and set it to 0 by default.
        else {
            $id = $jinput->get('id', 0);
        }

        return $form;
    }

    protected function loadFormData()
    {
        $data = $this->getItem();

        if(empty($data))
        {
            $data = array();
            $data['congtrinh_id'] = JRequest::getInt('congtrinhid', 0);            
        }
                        
        return $data;
    }
    
    public function getCongtrinh()
    {
        $id = JRequest::getInt('congtrinhid');

        $db = JFactory::getDBO();
        $query = $db->getQuery(true);

        $query->select('a.*');
        $query->from('#__congtrinh AS a');
        $query->where('a.id = ' . $id);

        $db->setQuery($query);
        
        $congtrinh = $db->loadObject();

        return $congtrinh;        
    }
    
    /**
     * Get the hosocanbo
     * @return string The message to be displayed to the user
     */
    public function getCanbo()
    {
        $id = JRequest::getInt('congtrinhid');

        $db = JFactory::getDBO();
        $query = $db->getQuery(true);

        $query->select('a.*');
        $query->from('#__congtrinh AS a');
        $query->where('a.id = ' . $id);

        $db->setQuery($query);
        
        $congtrinh = $db->loadObject();
                
        if ($congtrinh != NULL)
        {
            $query = $db->getQuery(true);
            $query->select('a.*');
            $query->from('#__hosocanbo AS a');
            $query->where('a.id = ' . $congtrinh->hosocanbo_id);
    
            $db->setQuery($query);
            $canbo = $db->loadObject();
            return $canbo;            
        }   
        else
        {
            return NULL;
        }     
    }  
    
    /**
     * Get the message
     * @return string The message to be displayed to the user
     */
    public function getPhong()
    {
        $id = JRequest::getInt('congtrinhid');

        $db = JFactory::getDBO();
        
        $query = $db->getQuery(true);

        $query->select('a.*');
        $query->from('#__congtrinh AS a');
        $query->where('a.id = ' . $id);

        $db->setQuery($query);
        
        $congtrinh = $db->loadObject();

        if ($congtrinh != NULL)
        {
            $query = $db->getQuery(true);
            $query->select('a.*');
            $query->from('#__hosocanbo AS a');
            $query->where('a.id = ' . $congtrinh->hosocanbo_id);
    
            $db->setQuery($query);
            $canbo = $db->loadObject();

            $query = $db->getQuery(true);
    
            $query->select('a.*');
            $query->from('#__phong AS a');
            $query->join('INNER', '#__congtac AS b ON b.phong_id = a.id');
            $query->where('b.hosocanbo_id = ' . $canbo->id);
            $query->where('b.taivi = 1');
            
            $db->setQuery($query);

            $phong = $db->loadObject();
            
            return $phong;
        }   
        
        return NULL;        
    }

    public function getKhoi() 
    {
        $db = JFactory::getDBO();
        $query = $db->getQuery(true);
        $donvi = $this->getDonvi();
        $phong = $this->getPhong();
        if ($donvi !== NULL)
        {
            $query = $db->getQuery(true);
            $query->select('a.*');
            $query->from('#__khoi AS a');
            $query->where('a.id = ' . $donvi->khoi_id);
            $db->setQuery($query);
            
            return $db->loadObject();            
        }
        elseif ($phong !== NULL)
        {
            $query = $db->getQuery(true);
            $query->select('a.*');
            $query->from('#__donvi AS a');
            $query->where('a.id = ' . $phong->donvi_id);
            $db->setQuery($query);            
            
            $tmp = $db->loadObject();
            if ($tmp !== NULL)
            {
                $query = $db->getQuery(true);
                $query->select('a.*');
                $query->from('#__khoi AS a');
                $query->where('a.id = ' . $tmp->khoi_id);
                $db->setQuery($query);
                
                return $db->loadObject();                            
            }
        }
        
        return NULL;
    }
        
    public function getDonvi() {
        $id = JRequest::getInt('congtrinhid');
      
        $db = JFactory::getDBO();

        $query = $db->getQuery(true);

        $query->select('a.*');
        $query->from('#__congtrinh AS a');
        $query->where('a.id = ' . $id);

        $db->setQuery($query);
        
        $congtrinh = $db->loadObject();
        
        if ($congtrinh != NULL)
        {
            $query = $db->getQuery(true);
            $query->select('a.*');
            $query->from('#__hosocanbo AS a');
            $query->where('a.id = ' . (int)$congtrinh->hosocanbo_id);
    
            $db->setQuery($query);
            $canbo = $db->loadObject();

            $query = $db->getQuery(true);
    
            $query->select('a.*');
            $query->from('#__donvi AS a');
            $query->join('INNER', '#__congtac AS b ON b.donvi_id = a.id');
            $query->where('b.hosocanbo_id = ' . $canbo->id);
            $query->where('b.taivi = 1');
            $db->setQuery($query);
            return $db->loadObject();
        }
        
        return NULL;
    }      
}